<script setup lang="ts">
import { createBuildingAPI, delBuildingAPI, getBuildingListAPI, updateBuildingAPI } from '@/apis/building';
import AuthBtn from '@/components/AuthBtn.vue';
import type { Building, BuildingListParams, BuildingParams } from '@/types/building';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import { onMounted, ref } from 'vue';

const params = ref<BuildingListParams>({
  page: 1,
  pageSize: 10,
  name: ''

})
const list = ref<Building[]>()
const total = ref(0)
const getLsit = async() => {
  const res = await getBuildingListAPI(params.value)
  console.log('res',res)
  list.value = res.data.rows
  total.value = res.data.total
}

onMounted(() => {
  getLsit()
})
// 模糊搜索
const onSearch = () => {
  params.value.page = 1
  getLsit()
}
// 表单初始数据
const initAddForm = () => {
  return {
    name: '',
    floors: undefined,
    area: undefined,
    propertyFeePrice: undefined
  }
}
// 表单数据
const addForm = ref<BuildingParams>(initAddForm())
const addFormRules = ref<FormRules<BuildingParams>>({
  name: [
    { required: true, message: '请输入楼宇名称', trigger: 'blur' },
    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
  ],
  floors: [
    { required: true, message: '请输入层数', trigger: 'blur' },
    { validator: (rule, value, callback) => {
      // 楼层数必须大于0且小于20
      if (value < 1 || value > 20) {
        callback(new Error('层数必须大于0且小于20'))
      } else {
        callback()
      }}
    }
  ],
  area: [
    { required: true, message: '请输入在管面积', trigger: 'blur' },
    { pattern: /^[1-9]\d*$/, message: '必须为正整数', trigger: 'blur' }
  ],
  propertyFeePrice: [
    { required: true, message: '请输入物业费单价', trigger: 'blur' },
    { pattern: /^[1-9]\d*$/, message: '必须为正整数', trigger: 'blur' }
  ]
})
// 弹窗显示标识
const buildingDialogFlag = ref(false)
// 表单 ref
const addFormRef = ref<FormInstance>()
// 打开 dialog
const onOpen = () => {
  buildingDialogFlag.value = true
}

// 关闭 dialog
const onClose = () => {
  // 重置表单数据
  addForm.value = initAddForm()
  // 重置表单验证
  addFormRef.value?.resetFields()
  buildingDialogFlag.value = false
}
// 提交按钮loading 标识
const submitLoading = ref(false)
// 提交表单
const onSubmit = async() => {
  try {
    // 整体表单验证
    await addFormRef.value?.validate()
    // 把按钮设置为加载状态(禁用提交，避免重复提交)
    submitLoading.value = true

    if(addForm.value.id){
      // 编辑接口
      await updateBuildingAPI(addForm.value)
      ElMessage.success('编辑成功')
    }else{
      // 调用接口，把数据提交给后端
    await createBuildingAPI(addForm.value)
    ElMessage.success('添加成功')
    }
    getLsit()
    submitLoading.value = false
    // 关闭 dialog
    onClose()
  } catch {
    // 提交失败，注意恢复按钮状态
    submitLoading.value = false
  }

}
// 删除按钮
const onDelete = async(id: number) => {
  
    ElMessageBox.confirm('此操作将永久删除, 是否继续?', '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async() => {
      // 删除
      await delBuildingAPI(id)
      ElMessage.success('删除成功')
      getLsit()
    }).catch(() => {})
  
}
// 编辑按钮
const onEdit = async(row: Building) => {
  // 打开 dialog
  buildingDialogFlag.value = true
  // 赋值
  addForm.value = {
    name: row.name,
    floors: row.floors,
    area: row.area,
    propertyFeePrice: row.propertyFeePrice,
    id: row.id
  }
}

</script>

<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">楼宇名称：</div>
      <el-input clearable placeholder="请输入楼宇名称" @clear="onSearch" v-model="params.name" class="search-main" />
      <el-button type="primary" @click="onSearch">查询</el-button>
    </div>
    <div class="create-container">
      <AuthBtn btn-perm="park:building:add_edit">
        <el-button type="primary"  @click="onOpen">添加楼宇</el-button>
      </AuthBtn>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="list">
        <el-table-column type="index" label="序号" width="120" />
        <el-table-column prop="name" label="楼宇名称"  />
        <el-table-column prop="floors" label="层数" />
        <el-table-column prop="area" label="在管面积(m²)" />
        <el-table-column prop="propertyFeePrice" label="物业费(元/m²)" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            {{ scope.row.status === 0 ? '空置中' : '租赁中' }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button size="small" @click="onEdit(row)" link type="primary">编辑</el-button>
            <el-button size="small" v-auth="'park:building:remove'" @click="onDelete(row.id)" link type="primary" :disabled="row.status === 1">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container" style="display: flex;justify-self: end;">
      <el-pagination 
        layout="total, prev, pager, next, sizes, jumper"
        :total="total"
        v-model:current-page="params.page" 
        v-model:page-size="params.pageSize"
        @change="getLsit()"
       />
    </div>
    <el-dialog :title="addForm.id ? '修改楼宇' : '添加楼宇'" width="600px" v-model="buildingDialogFlag" @close="onClose">
      {{ addForm }}
      <div class="form-container">
        <el-form label-width="100px" label-position="top" :model="addForm" :rules="addFormRules" ref="addFormRef">
          <el-form-item label="楼宇名称" prop="name">
            <el-input v-model="addForm.name" placeholder="请输入楼宇名称" />
          </el-form-item>
          <el-form-item label="层数" prop="floors">
            <el-input v-model="addForm.floors" placeholder="请输入层数" type="number" />
          </el-form-item>
          <el-form-item label="在管面积"  prop="area">
            <el-input v-model="addForm.area" placeholder="请输入在管面积" >
              <template #append>m²</template>
            </el-input>
          </el-form-item>
          <el-form-item label="物业费" prop="propertyFeePrice">
            <el-input v-model="addForm.propertyFeePrice" placeholder="请输入物业费" >
              <template #append>元/m²</template>
            </el-input>
          </el-form-item>

        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
           <el-button size="small" @click="onClose">取 消</el-button>
           <el-button size="small" type="primary" @click="onSubmit" :loading="submitLoading">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.building-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>